package org.qiyu.live.im.core.server.Servicer.impl;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.qiyu.live.im.constants.ImMsgCodeEnum;
import org.qiyu.live.im.core.server.Servicer.IRouterHandlerServicer;
import org.qiyu.live.im.core.server.Servicer.ImMsgAckCheckServicer;
import org.qiyu.live.im.core.server.common.ChannelHandlerContextCache;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.dto.ImMsgBody;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Description: //todo
 * @Author: 张广焱
 * @Date: 2023-12-10 20:28
 */
@Service
public class RouterHandlerServicerImpl  implements IRouterHandlerServicer {
    @Resource
    private ImMsgAckCheckServicer imMsgAckCheckServicer;
    @Override
    public void OnReceive(ImMsgBody imMsgBody) {
      //需要进行消息通知的userid
        Long userId = imMsgBody.getUserId();
        ChannelHandlerContext ctx = ChannelHandlerContextCache.get(userId);
        if (ctx!=null){
            String msgId = UUID.randomUUID().toString();
            imMsgBody.setMsgId(msgId);
            ImMsg respMsg = ImMsg.build(ImMsgCodeEnum.IM_BIZ_MSG.getCode(), JSON.toJSONString(imMsgBody));
            ctx.writeAndFlush(respMsg);
            //当im服务器推送了消息给客户端,然后我们需要记录下ack
            imMsgAckCheckServicer.recordMsgAck(imMsgBody,1);
            imMsgAckCheckServicer.sendDelayMsg(imMsgBody);
        }

    }
}
